<script setup lang='ts'>
defineOptions({ name: 'AppSportsPageEventBuilder' })

const { allSportsCount, allSportsSi } = storeToRefs(useSportsStore())
const { sportsEventTimeRang } = storeToRefs(useTransferStore())

/** 球种id筛选 0全部 */
const filterCurrent = ref(allSportsSi.value[0]?.toString() ?? '1')
/** 时间筛选 0全部 */
const filterCurrentTime = ref(sportsEventTimeRang.value)

// 体育项目选择了所有
const isFilterCurrentAll = computed(() => filterCurrent.value === '0')
// 已选的体育项目Array
const currentSiArr = computed(() => filterCurrent.value.split(',').map((a) => +a))
// 体育项目选项
const filterSportsList = computed(() => {
  const _all = { label: $t('spt_all_spt'), value: '0', icon: '' }
  if (allSportsCount.value && allSportsCount.value.list && allSportsCount.value.list.length > 0) {
    const arr = allSportsCount.value.list.map((item) => {
      return {
        ...item,
        label: item.sn,
        value: item.si.toString(),
        icon: item.spic,
        count: filterCurrent.value.split(',').length - 1
      }
    })

    return [_all, ...arr]
  }
  return [_all]
})
// 时间选项
const filterTimeList = computed(() => {
  let count3h = 0
  let count24h = 0
  let count48h = 0
  let countAll = 0

  if (allSportsCount.value && allSportsCount.value.list) {
    count3h = isFilterCurrentAll.value ? allSportsCount.value.list.reduce((acc, cur) => {
      return acc + cur.o3c
    }, 0)
      : allSportsCount.value.list.filter((a) => currentSiArr.value.includes(a.si)).reduce((acc, cur) => {
        return acc + cur.o3c
      }, 0)
    count24h = isFilterCurrentAll.value ? allSportsCount.value.list.reduce((acc, cur) => {
      return acc + cur.o24c
    }, 0)
      : allSportsCount.value.list.filter((a) => currentSiArr.value.includes(a.si)).reduce((acc, cur) => {
        return acc + cur.o24c
      }, 0)
    count48h = isFilterCurrentAll.value ? allSportsCount.value.list.reduce((acc, cur) => {
      return acc + cur.o48c
    }, 0)
      : allSportsCount.value.list.filter((a) => currentSiArr.value.includes(a.si)).reduce((acc, cur) => {
        return acc + cur.o48c
      }, 0)
    countAll = isFilterCurrentAll.value ? allSportsCount.value.c :
      allSportsCount.value.list.filter((a) => currentSiArr.value.includes(a.si)).reduce((acc, cur) => {
        return acc + cur.c
      }, 0)
  }

  return [
    { label: $t('spt_3h'), value: '8', count: count3h },
    { label: $t('spt_24h'), value: '9', count: count24h },
    { label: $t('spt_48h'), value: '10', count: count48h },
    { label: $t('spt_all'), value: '0', count: countAll },
  ]
})

let timer: any = null
const list = ref<ISportEventInfo[]>([])
const page = ref(1)
const pageSize = ref(24)
const total = ref(0)
const params = computed(() => {
  return {
    si: currentSiArr.value,
    m: +filterCurrentTime.value,
    page: page.value,
    page_size: pageSize.value
  }
})
const { run, runAsync, } = useRequest(ApiSportEventList, {
  onSuccess(res) {
    if (res.d) {
      total.value = res.t
      list.value = res.d
    }
    else {
      total.value = 0
      list.value = []
    }
  }
})
/** 👷 分页、定时器、监听更新数据 start 👷 */
function startTimer() {
  stopTimer()
  timer = setInterval(() => {
    getData()
  }, 120000)
}
function stopTimer() {
  if (timer !== null) {
    clearInterval(timer)
    timer = null
  }
}
function getData() {
  run(params.value)
}
function prePage() {
  page.value = page.value - 1
  getData()
}
function nextPage() {
  page.value = page.value + 1
  getData()
}
function reset() {
  page.value = 1
  total.value = 0
}
function updateDataByMqtt(data: ISportEventList[]) {
  list.value = sportsEventInfoListUpdateByMqtt(list.value, data)
}
/** 🚧 分页、定时器、监听更新数据 end 🚧 */

// 初始化数据
function initData() {
  return new Promise((resolve) => {
    let a = 0
    const t = setInterval(() => {
      a++
      if (allSportsSi.value && allSportsSi.value.length > 0) {
        clearInterval(t)
        filterCurrent.value = allSportsSi.value[0].toString()
        runAsync(params.value).finally(() => {
          resolve(true)
        })
      }
      else if (a > 300) {
        clearInterval(t)
        resolve(true)
      }
    }, 50)
  })
}

// 防抖
const handleFilterChange = debounce(() => {
  reset()
  getData()
  startTimer()
}, 500)

watch([filterCurrent, filterCurrentTime], () => {
  handleFilterChange()
})

onActivated(() => {
  startTimer()
  appEventBus.on(EventBusNames.SPORTS_DATA_CHANGE_BUS, updateDataByMqtt)
})
onDeactivated(() => {
  stopTimer()
  appEventBus.off(EventBusNames.SPORTS_DATA_CHANGE_BUS, updateDataByMqtt)
})
onBeforeUnmount(() => {
  stopTimer()
  appEventBus.off(EventBusNames.SPORTS_DATA_CHANGE_BUS, updateDataByMqtt)
})

await application.allSettled([initData()])
</script>

<template>
  <div>
    <div class="flex relative mb-[16px]">
      <AppSportsMarketFilter type="sports" v-model="filterCurrent" :list="filterSportsList" />
      <AppSportsMarketFilter type="time" v-model="filterCurrentTime" :list="filterTimeList" :cols="2" />
    </div>

    <div v-show="list.length > 0">
      <div class="grid gap-[16px]">
        <div class="min-w-0" v-for="event in list" :key="event.ei">
          <AppSportsMarketInfo :data="event" />
        </div>
      </div>
      <AppSportsPagination v-if="total > pageSize" @previous="prePage" @next="nextPage" :total="total" :page="page"
        :page-size="pageSize" class="mt-[16px]" />
    </div>
    <AppSportsEmpty v-if="list.length === 0" />
  </div>
</template>

<style lang='scss' scoped></style>
